package com.icebartech.base.modules.common.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.icebartech.base.modules.common.dto.VerifyCodeDTO;
import com.icebartech.base.modules.common.service.VerifyCodeService;
import com.icebartech.core.components.AliyunOSSComponent;
import com.icebartech.core.components.RedisComponent;
import com.icebartech.core.conf.SiteProperties;
import com.icebartech.core.enums.CommonResultCodeEnum;
import com.icebartech.core.utils.VerifyCodeUtils;
import com.icebartech.core.vo.ResponseData;

@Service
public class VerifyCodeServiceImpl implements VerifyCodeService {
	
	@Autowired
	private SiteProperties siteProperties;
	
	@Autowired
	private AliyunOSSComponent aliyunOSSComponent;
	
	@Autowired
	private RedisComponent redisComponent;
	
	private static String random_code_group = "random_code";

	@Override
	public ResponseData<VerifyCodeDTO> randowVerifyCode() {
		ResponseData<VerifyCodeDTO> resp = ResponseData.builder(null, CommonResultCodeEnum.FAIL);
		try {
			//生成随机字串
			String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
			//生成图片
			int w = 100, h = 45;
			
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			VerifyCodeUtils.outputImage(w, h, baos, verifyCode);
			
			//上传到阿里云
			String fileKey = aliyunOSSComponent.uploadFile(baos.toByteArray(), "jpeg", null);
			if(StringUtils.isNotEmpty(fileKey)) {
				String key = UUID.randomUUID().toString();
				redisComponent.putRedisCache(random_code_group, key, verifyCode, 900);//缓存15分钟
				String url = aliyunOSSComponent.getFileUrl(fileKey);
				VerifyCodeDTO codeDTO = new VerifyCodeDTO();
				codeDTO.setCodeUrl(url);
				codeDTO.setToken(key);
				resp = ResponseData.builder(codeDTO, CommonResultCodeEnum.SUCCESS);
			}else {
				resp = ResponseData.builderError(null, "上传阿里云，生成验证码失败");
			}
		}catch(Exception e) {
			resp = ResponseData.builderError(null, e.getMessage());
		}
		return resp;
	}

	@Override
	public ResponseData<Boolean> checkVerifyCode(String token, String randomCode) {
		ResponseData<Boolean> resp = ResponseData.builder(false, CommonResultCodeEnum.FAIL);
		String value = redisComponent.getRedisCache(random_code_group, token);
		boolean flag = false;
		if(randomCode.equalsIgnoreCase(value)) {
			flag = true;
		}
		resp = ResponseData.builder(flag, CommonResultCodeEnum.SUCCESS);
		return resp;
	}

}
